<template>
  <div class="app-container">
    <el-card>
      <div class="mb-30">
        <h3 class="mb-20 ft-16">门店信息</h3>
        <p>{{ storeInfoText }}</p>
      </div>
      <el-row>
        <h3 class="mb-20 ft-16">核销概况</h3>
        <el-col class="text-center" :span="10">
          <LiveOverview :tabs="tabs" :show-time="false" :show-item-class="false" />
        </el-col>
        <el-col :span="14">
          <BarChart :title="title" :data-x="dataX" :data-y="dataY" :showZoom="true" />
        </el-col>
      </el-row>

      <div class="flex justify-between">
        <div>
          <el-form :inline="true">
            <el-form-item label="兑换人信息：" label-width="110px">
              <ScrollSelect
                placeholder="请选择用户信息"
                :selected-value="formOption.userId"
                :get-list-methods="getListMethods"
                :get-list-format="getListFormat"
                :clearable="true"
                search-key="nickNameOrMobile"
                @selectedChange="selectedChange"
              />
            </el-form-item>

            <el-form-item label="礼品券名称：" label-width="100px">
              <el-input v-model="formOption.couponName" placeholder="请输入礼品券名称搜索" />
            </el-form-item>

            <el-form-item label-width="100px">
              <el-date-picker
                v-model="formOption.time"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 320px"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button class="ml-20" type="primary" @click="searchHandle">搜索</el-button>
              <el-button class="ml-20" @click="reset">重置</el-button>
              <el-button @click="exportFile">导出</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <PageTable
        :options="options"
        :columns="columns"
        :data="dataSource"
        @selectChange="selectChange"
      />

      <Pagination
        v-show="total > 0"
        :total="total"
        :pageNo.sync="listQuery.pageNo"
        :pageSize.sync="listQuery.pageSize"
        @pagination="getStoreSaleList"
      />
    </el-card>
  </div>
</template>

<script>
import { STORE_TYPE } from '@/enum/coupon'
import { export2Excel } from '@/utils/export'
import { useFilterBaseStatistics } from '@/hooks'
export default {
  name: 'WriteOff',
  components: {},
  props: {},
  data() {
    return {
      title: {
        text: '近30天扫码兑换概况',
        left: '1%'
      },
      dataX: [],
      dataY: [],
      tooltip: {
        trigger: 'axis'
      },
      formOption: {
        time: [],
        userId: '',
        couponName: ''
      },
      btnList: [
        {
          type: 'primary',
          label: '搜索',
          onClick: () => {
            this.listQuery.pageNo = 1
            this.getStoreSaleList()
          }
        },
        {
          label: '导出',
          onClick: () => {
            this.exportFile()
          }
        }
      ],
      listQuery: {
        pageNo: 1,
        pageSize: 10
      },
      total: 0,
      columns: [
        {
          prop: 'couponName',
          label: '礼品券名称'
        },
        {
          prop: 'couponCode',
          label: '兑换码',
          render: (h, { row }) => {
            return <div style={'color: #409eff'}>{row.couponCode}</div>
          }
        },
        {
          label: '兑换人信息',
          render: (h, { row }) => {
            return (
              <div>
                <div class={row.baseUserInfo.isNew ? 'flex' : ''}>
                  <span>{row.baseUserInfo.nickName}</span>
                  {row.baseUserInfo.isNew ? <el-tag type="danger">新用户</el-tag> : ''}
                </div>
                <div>{row.baseUserInfo.mobile}</div>
              </div>
            )
          }
        },
        {
          prop: 'count',
          label: '兑换张数',
          render: () => {
            return <div>x1</div>
          }
        },
        {
          prop: 'integral',
          label: '获得积分',
          render: (h, { row }) => {
            return <span>+{row.integral}</span>
          }
        },
        {
          prop: 'exchange_way',
          label: '兑换方式',
          render: () => {
            return <span>小程序扫码</span>
          }
        },
        {
          prop: 'createdTime',
          label: '生成时间'
        },
        {
          prop: 'usedTime',
          label: '兑换时间'
        }
      ],
      options: {
        border: true,
        select: true
      },
      ids: [],
      dataSource: [],
      selectList: [],
      getListMethods: params => {
        return this.getUserSelectList(params)
      },
      getListFormat: (list = []) => {
        // 下拉框数据格式
        return list.map(({ nickName, mobile, id }) => ({
          label: `${nickName} ${mobile}`,
          value: id
        }))
      },
      tabs: [
        {
          isShow: true,
          key: 'saleSum',
          label: '总核销张数'
        },
        {
          isShow: true,
          key: 'currMonthSaleSum',
          label: '本月核销'
        }
      ],
      storeInfoText: ''
    }
  },
  computed: {
    id() {
      return this.$route.query?.id
    }
  },
  watch: {
    selectList(list) {
      this.ids = list?.map(item => item.id)
    }
  },
  created() {
    this.countStoreSale()
    this.getActivityCount()
    this.getStoreSaleList()
    this.getChannelStoreDetail()
  },
  methods: {
    // 获取门店信息
    async getChannelStoreDetail() {
      const { data } = await this.$http.coupon.channelApi.getChannelStoreDetail(this.id)
      this.storeInfoText = `【${STORE_TYPE[data.storeType]}】 ${data.storeName}`
    },
    // 获取用户信息
    async getUserSelectList(params) {
      const {
        data: { records }
      } = await this.$http.user.user.getUserSelectList({ params })
      return records
    },
    // 监听选择用户信息
    selectedChange(id) {
      this.formOption.userId = id
    },
    // 获取30天兑换记录统计
    async getActivityCount() {
      const { data } = await this.$http.coupon.activityApi.getActivityCount({ storeId: this.id })
      const list = Object.entries(data)
        .map(item => {
          return {
            time: item[0],
            value: item[1]
          }
        })
        .sort((a, b) => {
          return this.$moment(a.time).unix() - this.$moment(b.time).unix()
        })
      this.dataX = list.map(item => item.time)
      this.dataY = [list.map(item => item.value)]
    },
    // 获取礼品券兑换明细
    async countStoreSale() {
      const { data } = await this.$http.coupon.voucherApi.countStoreSale({ storeId: this.id })
      this.tabs = useFilterBaseStatistics(this.tabs, data)
    },
    // 获取礼品销售列表
    async getStoreSaleList() {
      const params = {
        storeId: this.id,
        ...this.listQuery
      }
      const { userId, couponName, time } = this.formOption
      if (userId) params.userId = userId
      if (couponName) params.couponName = couponName
      if (time) params.startTime = time[0] && time[0]
      if (time) params.endTime = time[1] && time[1]
      const {
        data: { total, records }
      } = await this.$http.coupon.voucherApi.getStoreSaleList(params)
      this.total = total
      this.dataSource = records
    },
    // 导出
    async exportFile() {
      if (!this.ids.length) return this.$message.error('请选择要导出的数据！')
      const headerData = this.columns.filter(item => item.prop).map(item => item.label)
      headerData.splice(2, 0, '兑换人')
      headerData.splice(3, 0, '兑换人手机号')

      const filterData = this.columns.filter(item => item.prop).map(item => item.prop)
      filterData.splice(2, 0, 'nickName')
      filterData.splice(3, 0, 'mobile')

      const list = this.$lodash.cloneDeep(this.selectList)
      const tableData = list.map(item => {
        item.count = 'x1'
        item.integral = `+${item.integral}`
        item.exchange_way = '小程序扫码'
        item.nickName = item.baseUserInfo.nickName
        item.mobile = item.baseUserInfo.mobile
        return item
      })
      export2Excel(headerData, tableData, filterData, '渠道礼品券核销详情', () => {
        this.$message.success('导出成功！')
      })
    },
    // 监听选择行数据
    selectChange(list) {
      this.selectList = list
    },
    // 搜索
    searchHandle() {
      this.listQuery.pageNo = 1
      this.getStoreSaleList()
    },
    reset() {
      this.listQuery.pageNo = 1
      this.formOption = {
        time: [],
        userId: '',
        couponName: ''
      }
      this.getStoreSaleList()
    }
  }
}
</script>
